var defaultOptions: Options = {
    format: 'image/png',
    quality: 0.92,
    width: undefined,
    height: undefined,
    Canvas: undefined,
    crossOrigin: undefined
};



type Image = string;

type ImageSource = Image | { src: Image; x?: number | undefined; y?: number | undefined; opacity?: number | undefined, color?: string, fontSize?: string, format?: 'data' | 'image' | 'text' };

interface Options {
    /**
     * A DOMString indicating the image format.
     *
     * @default 'image/png'
     */
    format?: string | undefined;

    /**
     * A number between `0` and `1` indicating image quality if the requested format is `'image/jpeg'` or `'image/webp'`.
     *
     * @default 0.92
     */
    quality?: number | undefined;

    /**
     * The width in pixels the rendered image should be. Defaults to the width of the widest source image.
     *
     * @default undefined
     *
     * @example
     * mergeImages(['/body.png', '/eyes.png', '/mouth.png'], {
     *   width: 128,
     * })
     *   .then(b64 => ...);
     *   // ...
     */
    width?: number | undefined;

    /**
     * The height in pixels the rendered image should be. Defaults to the height of the tallest source image.
     *
     * @default undefined
     *
     * @example
     * mergeImages(['/body.png', '/eyes.png', '/mouth.png'], {
     *   height: 128,
     * })
     *   .then(b64 => ...);
     *   // ...
     */
    height?: number | undefined;

    /**
     * `Canvas` implementation to be used to allow usage outside of the browser. e.g Node.js with [node-canvas](https://github.com/Automattic/node-canvas).
     *
     * @default undefined
     *
     * @example
     * import mergeImages = require('merge-images');
     * import { Canvas, Image } from 'canvas';
     *
     * mergeImages(['./body.png', './eyes.png', './mouth.png'], {
     *   Canvas: Canvas,
     *   Image: Image
     * })
     *   .then(b64 => ...);
     *   // ...
     */
    Canvas?: any;

    /**
     * `Image` implementation to be used to allow usage outside of the browser. e.g Node.js with node-canvas.
     * This should be a valid image source for the node-canvas `Image` rather than a DOM `Image`.
     * Check the [node-canvas](https://github.com/Automattic/node-canvas) docs for more information on valid Image sources.
     *
     * @default undefined
     *
     * @example
     * import mergeImages = require('merge-images');
     * import { Canvas, Image } from 'canvas';
     *
     * mergeImages(['./body.png', './eyes.png', './mouth.png'], {
     *   Canvas: Canvas,
     *   Image: Image
     * })
     *   .then(b64 => ...);
     *   // ...
     */
    Image?: any;

    /**
     * The `crossOrigin` attribute that `Image` instances should use. e.g `anonymous` to [support CORS-enabled images](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image).
     *
     * @default undefined
     */
    crossOrigin?: "anonymous" | "use-credentials" | "" | undefined;
}

// Return Promise
export default function mergeImages(sources: ImageSource[], options = defaultOptions) {
    if (sources === void 0) sources = [];
    if (options === void 0) options = {};

    return new Promise(function (resolve) {
        options = Object.assign({}, defaultOptions, options);

        // Setup browser/Node.js specific variables
        var canvas = window.document.createElement('canvas');
        var Image = window.Image;

        // Load sources
        var images = sources.filter(e => e.format !== 'text').map(function (source) {
            return new Promise(function (resolve, reject) {
                // Convert sources to objects
                if (source.constructor.name !== 'Object') {
                    source = { src: source };
                }

                // Resolve source and img when loaded
                var img = new Image();
                img.crossOrigin = options.crossOrigin;
                img.onerror = function () { return reject(new Error('Couldn\'t load image')); };
                img.onload = function () { return resolve(Object.assign({}, source, { img: img })); };
                img.src = source.src;
            });
        });

        const texts = sources.filter(e => e.format === 'text')

        // Get canvas context
        var ctx = canvas.getContext('2d') as CanvasRenderingContext2D
        if (!ctx) {
            return Error('无法使用画布')
        }



        // When sources have loaded
        resolve(Promise.all(images)
            .then(function (images) {
                // Set canvas dimensions
                var getSize = function (dim) { return options[dim] || Math.max.apply(Math, images.map(function (image) { return image.img[dim]; })); };
                canvas.width = getSize('width');
                canvas.height = getSize('height');

                // Draw images to canvas
                images.forEach(function (image) {
                    ctx.globalAlpha = image.opacity ? image.opacity : 1;
                    return ctx?.drawImage(image.img, image.x || 0, image.y || 0);
                });

                texts.forEach(e => {
                    if (typeof e === 'string') {
                        ctx.font = '40px serif'
                        ctx.fillText(e, 0, 0)
                    } else {
                        ctx.font = `${e.fontSize} Microsoft YaHei, Arial`
                        ctx.fillStyle = e.color
                        ctx.fillText(e.src, e.x, e.y, canvas.width * 0.7)
                    }
                })

                if (options.Canvas && options.format === 'image/jpeg') {
                    // Resolve data URI for node-canvas jpeg async
                    return new Promise(function (resolve, reject) {
                        canvas.toDataURL(options.format, {
                            quality: options.quality,
                            progressive: false
                        });
                    });
                }

                // Resolve all other data URIs sync
                return canvas.toDataURL(options.format, options.quality);
            }));
    });
};

export function getBase64Image(img: HTMLImageElement) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, img.width, img.height);
    var dataURL = canvas.toDataURL("image/png");
    return dataURL
}